package com.demo.rydemo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author ry
 * @Description  配置多种跨域方式
 * @Date 2020/8/7 15:52
 */

//@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        //解决跨域的问题
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,X-App-Id, X-Token");
        response.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");

        filterChain.doFilter(request,response);
//        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$","");
//        boolean allowePath =  ALLOWED_PATHS.contains(path);
//
//        if (!allowePath) {  //需要拦截的方法
//            Object aa = request.getSession().getAttribute("user");
//            if (aa != null) {
//                filterChain.doFilter(request,response);
//            }
//            else {
//                response.getWriter().write("noLogin");
//            }
//        } else {  //不需要被拦截的方法
//            //直接放行
//            filterChain.doFilter(request,response);
//        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
